import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

final counterProvider = StateProvider((ref) => 0);
final nameProvider = StateProvider((ref) => "");

// 创建组合状态
class CombinedState {
  final int counter;
  final String name;

  CombinedState(this.counter, this.name);
}

// 创建组合的Provider
final combinedProvider = Provider((ref) {
  final counter = ref.watch(counterProvider);
  final name = ref.watch(nameProvider);
  return CombinedState(counter, name);
});

class User {
  final String name;
  final int age;
  User({required this.name, required this.age});
  User copyWith({String? name, int? age}) {
    return User(name: name ?? this.name, age: age ?? this.age);
  }
}

final userProvider = StateProvider((ref) => User(name: "John", age: 30));

final userIdProvider = StateProvider((ref) => 1);

// 定义 Notifier
class CounterNotifier extends Notifier<int> {
  @override
  int build() => 0;

  void increment() => state++;
}

// 定义 NotifierProvider
final counterNotifierProvider = NotifierProvider<CounterNotifier, int>(
  () => CounterNotifier(),
);

// 定义状态类（包含所有需要管理的属性）
class AppState {
  final String name;
  final int age;
  final bool isPremium;

  const AppState({this.name = 'John', this.age = 30, this.isPremium = false});

  // 可选：添加 copyWith 方法方便部分更新
  AppState copyWith({String? name, int? age, bool? isPremium}) {
    return AppState(
      name: name ?? this.name,
      age: age ?? this.age,
      isPremium: isPremium ?? this.isPremium,
    );
  }
}

// 定义 Notifier 子类
class AppStateNotifier extends Notifier<AppState> {
  @override
  AppState build() {
    // 返回初始状态
    return AppState();
  }

  // 定义操作方法（修改状态）
  void updateName(String newName) {
    state = state.copyWith(name: newName);
  }

  void incrementAge() {
    state = state.copyWith(age: state.age + 1);
  }

  void togglePremium() {
    state = state.copyWith(isPremium: !state.isPremium);
  }
}

// 创建 Provider
final appStateProvider = NotifierProvider<AppStateNotifier, AppState>(
  AppStateNotifier.new,
);

class AsyncAppStateNotifier extends AsyncNotifier<AppState> {
  @override
  Future<AppState> build() async {
    // 可以从本地存储或API初始化状态
    return AppState(name: 'Loading...', age: 0);
  }

  Future<void> fetchUser() async {
    state = const AsyncValue.loading(); // 显示加载状态
    try {
      // final user = await api.fetchUser(); // 模拟API调用
      // state = AsyncValue.data(AppState(name: user.name, age: user.age));
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

final asyncAppStateProvider = AsyncNotifierProvider<AsyncAppStateNotifier, AppState>(
  AsyncAppStateNotifier.new,
);
